from rest_framework import serializers
from django.contrib.auth import get_user_model
from .models import *
User = get_user_model()


class UserRegSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'


class OptionsTypeSerializer(serializers.ModelSerializer):
    option_set = serializers.StringRelatedField(many=True)

    class Meta:
        model = Option
        fields = ('value', 'option_set')
        depth = 2


class CustomerSerializer(serializers.ModelSerializer):

    def create(self, validated_data):
        id_pre = Customer.objects.last().pk  # 新pk是表中最新一条数据的pk+1
        A001 = 'K-' + str(int(id_pre[2:]) + 1).zfill(5)
        validated_data['A001'] = A001
        return Customer.objects.create(**validated_data)

    class Meta:
        model = Customer
        fields = '__all__'


class ContactsSerializer(serializers.ModelSerializer):
    queryset = Customer.objects.all()
    F001 = serializers.SlugRelatedField(slug_field='B001', queryset=queryset, label='客户联系人')

    class Meta:
        model = Contacts
        fields = '__all__'